package service

import (
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateTrain
//@description: 创建Train记录
//@param: train model.Train
//@return: err error

func CreateTrain(train model.Train) (err error) {
	err = global.GVA_DB.Create(&train).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteTrain
//@description: 删除Train记录
//@param: train model.Train
//@return: err error

func DeleteTrain(train model.Train) (err error) {
	err = global.GVA_DB.Delete(&train).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteTrainByIds
//@description: 批量删除Train记录
//@param: ids request.IdsReq
//@return: err error

func DeleteTrainByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]model.Train{},"id in ?",ids.Ids).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateTrain
//@description: 更新Train记录
//@param: train *model.Train
//@return: err error

func UpdateTrain(train model.Train) (err error) {
	err = global.GVA_DB.Save(&train).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetTrain
//@description: 根据id获取Train记录
//@param: id uint
//@return: err error, train model.Train
// 根据ID获取时添加.Preload("Lines")预加载可以同时获取一对多中多的信息
func GetTrain(TrainId uint64) (err error, train model.Train) {
	err = global.GVA_DB.Where("id = ?", TrainId).Preload("Lines").First(&train).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetTrainInfoList
//@description: 分页获取Train记录
//@param: info request.TrainSearch
//@return: err error, list interface{}, total int64

func GetTrainInfoList(info request.TrainSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&model.Train{})
    var trains []model.Train
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.TrainNo != "" {
        db = db.Where("`train_no` LIKE ?","%"+ info.TrainNo+"%")
    }
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Preload("Lines").Find(&trains).Error
	return err, trains, total
}

// 动车设置路线关联
func SetTrainLines(train *model.Train) error {
	var t model.Train
	global.GVA_DB.Preload("Lines").First(&t, "id = ?", train.ID)
	err := global.GVA_DB.Model(&t).Association("Lines").Replace(&train.Lines)
	return err
}

// 动车设置路线关联
func AddTrainLines(lines []model.Lines, trainId uint64) (err error) {
	var train model.Train
	train.ID = trainId
	train.Lines = lines
	err = SetTrainLines(&train)
	return err
}